using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using log4net.Core;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;

namespace Quiki
{
    public class NVelocityTemplatingEngine : ITemplatingEngine
    {
        public NVelocityTemplatingEngine(ILogger logger)
        {
            this.logger = logger;
        }

        public string ExpandTemplate(string templateFileName, IDictionary<string, object> properties)
        {
            if (false == File.Exists (templateFileName))
            {
                logger.Log(Level.Error, "Template file '{0}' does not exist", templateFileName);
                return null;
            }

            string directoryName = Path.GetDirectoryName (templateFileName);
            if (String.IsNullOrEmpty (directoryName))
                directoryName = ".";
            string templateDir = Path.GetFullPath (directoryName);

            VelocityEngine velocity = new VelocityEngine ();
            velocity.SetProperty (RuntimeConstants.RESOURCE_LOADER, "file");
            velocity.SetProperty (RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDir);
            velocity.Init ();

            Template template = velocity.GetTemplate (
                Path.GetFileName (templateFileName),
                new UTF8Encoding (false).WebName);

            VelocityContext velocityContext = new VelocityContext ();
            foreach (KeyValuePair<string, object> pair in properties)
                velocityContext.Put(pair.Key, pair.Value);

            using (StringWriter writer = new StringWriter (CultureInfo.InvariantCulture))
            {
                template.Merge(velocityContext, writer);
                return writer.ToString();
            }
        }

        private readonly ILogger logger;
    }
}